<template>
    <div class="login-bg">
        <div class="login-container">
            <div class="login-header">
                <img class="logo mr10" src="../../assets/img/logo.svg" alt="" />
                <div class="login-title">后台管理系统</div>
            </div>
            <el-form :model="param" :rules="rules" size="large">
                <el-form-item prop="userId">
                    <el-input v-model="param.userId" placeholder="请输入您的账号">
                        <template #prepend>
                            <el-icon>
                                <User />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input type="password" placeholder="请输入您的密码" v-model="param.password" @keyup.enter="submitForm">
                        <template #prepend>
                            <el-icon>
                                <Lock />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <div class="pwd-tips">
                    <el-checkbox class="pwd-checkbox" v-model="checked" label="记住密码" />
                    <el-link type="primary" @click="$router.push('/reset-pwd')">忘记密码</el-link>
                </div>
                <el-button class="login-btn" type="primary" size="large" @click="submitForm">登录</el-button>
                <!-- <p class="login-text">
                    没有账号？<el-link type="primary" @click="$router.push('/register')">立即注册</el-link>
                </p> -->
            </el-form>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useTabsStore } from '@/store/tabs';
import { usePermissStore } from '@/store/permiss';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { login } from '@/api';

interface LoginInfo {
    userId: string;
    password: string;
}

const lgStr = localStorage.getItem('login-param');
const defParam = lgStr ? JSON.parse(lgStr) : null;
const checked = ref(lgStr ? true : false);

const router = useRouter();
// 默认登录参数设置
const param = reactive<LoginInfo>({
    userId: defParam ? defParam.userId : '',
    password: defParam ? defParam.password : '',
});
// 账号密码输入规则
const rules: FormRules = {
    userId: [
        {
            required: true,
            message: '请输入账号',
            trigger: 'blur',
        },
        {
            validator: (rule, value, callback) => {
                const reg = /^\d+$/; // 正则表达式：只允许数字  
                if (!reg.test(value)) {
                    callback(new Error('账号必须为数字'));
                } else {
                    callback();
                }
            },
            trigger: ['blur', 'change'], // 可以根据需要调整触发事件  
        },
    ],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
};
const permiss = usePermissStore();
let result = ref()
const submitForm = async () => {
    try {
        result.value = await login(param)
        if (result.value.data.data) {
            ElMessage.success('登录成功');
            const userRole = param.userId === '100007' ? 'admin' : 'user';
            localStorage.setItem('vuems_name', userRole);
            const keys = permiss.defaultList[userRole];
            permiss.handleSet(keys); // 更新权限  

            localStorage.setItem('loginUserInfo', JSON.stringify(result.value.data.data));
            //如果选择保存登录参数，当参数存在的时候
            if (checked.value) {
                localStorage.setItem('login-param', JSON.stringify(param));
            } else {
                localStorage.removeItem('login-param');
            }
            router.push('/dashboard'); // 确保路由正确处理重载  
        } else {
            ElMessage.error('登录失败，检查账号密码！');
            return false;
        }
    } catch (error) {
        ElMessage.error('请求接口失败，检查网络！');
        return false;
    }
};

const tabs = useTabsStore();
tabs.clearTabs();
</script>

<style scoped>
.login-bg {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100vh;
    background: url(../../assets/img/login-bg.jpg) center/cover no-repeat;
}

.login-header {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 40px;
}

.logo {
    width: 35px;
}

.login-title {
    font-size: 22px;
    color: #333;
    font-weight: bold;
}

.login-container {
    width: 450px;
    border-radius: 5px;
    background: #fff;
    padding: 40px 50px 50px;
    box-sizing: border-box;
}

.pwd-tips {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    margin: -10px 0 10px;
    color: #787878;
}

.pwd-checkbox {
    height: auto;
}

.login-btn {
    display: block;
    width: 100%;
}

.login-tips {
    font-size: 12px;
    color: #999;
}

.login-text {
    display: flex;
    align-items: center;
    margin-top: 20px;
    font-size: 14px;
    color: #787878;
}
</style>
